#include <QtGui>
#include <QtXml>
#include "stage1.h"
#include "attribute.h"
//
Stage1::Stage1():Stage()
{
	_treeView = 0;
	_attributes = new AttributesModel;
	
	connect(_attributes,SIGNAL(attrChanged(int,Attribute*)),this,SIGNAL(attrChanged(int,Attribute*)));
}

void Stage1::setTreeView(DragTreeView *tv)
{
	_treeView = tv;
	_treeView->setModel(_attributes);
	_treeView->header()->hide();
	_treeView->setRootIsDecorated(false);
	_treeView->setDragEnabled(true);
	_treeView->setAcceptDrops(true);
	_treeView->setContextMenuPolicy(Qt::CustomContextMenu);
	connect(_treeView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(slotAttributeMenu(QPoint)));
}
//
//
//
Stage1::~Stage1()
{
	_attributes->clear();
	//_attributes = 0;
}
//
void Stage1::slotAddAttribute()
{
	//AddAttribute ad;
	int num = _attributes->newNumber();
	QMap<QString,QString> params;
	params["number"] = QString("%1").arg(num);
	params["alias"]  = trUtf8("Координата%1").arg(num);
	params["name"]   = _attributes->newName();
	_attributes->addAttribute(params);	
	
	//_treeView->
}
//
void Stage1::clear()
{
	if(_attributes) _attributes->clear();
	Attribute::num=1;
}
//
bool Stage1::load(QDomElement elem)
{
	if(elem.isNull()) return false;
	
	QDomNode node = elem.firstChildElement("attribute");
	while(!node.isNull()){
		if(!_attributes->addAttribute(node)){
			qDebug("attribute not added");
		}
		node = node.nextSiblingElement("attribute");
	}
	
	return true;
}
//
QDomElement Stage1::xml()
{
	QDomElement node;
	QDomDocument doc;
	node = doc.createElement("stage1");
	if(node.isNull()){
		qDebug("node is null");
	}
	_attributes->xml(node);
	return node;
}
//
void Stage1::slotEditAttribute()
{
	QModelIndexList indexes  = _treeView->selectionModel()->selectedIndexes();
	if(indexes.size()) _attributes->editAttribute(indexes.first());

//	_attributes->editCurrentAttribute();
}
//
void Stage1::slotRemoveAttribute()
{// remove current attribute from drag widget
	if (QMessageBox::warning(NULL,trUtf8("umsmanager"),trUtf8("Вы действительно хотите удалить координату?"),QMessageBox::Yes | QMessageBox::No)==QMessageBox::Yes)
		_attributes->removeAttributes(_treeView->selectionModel()->selectedIndexes());
}
//
void Stage1::slotAttributeMenu(const QPoint &point)
{
	QMenu menu;
	connect(menu.addAction(trUtf8("Создать")),SIGNAL(triggered()),this,SLOT(slotAddAttribute()));
	if(_treeView->selectionModel()->selectedIndexes().count()!=0){
		connect(menu.addAction(trUtf8("Удалить")) ,SIGNAL(triggered()),this,SLOT(slotRemoveAttribute()));		
	}
	menu.exec(_treeView->mapToGlobal(point));
}
//
void Stage1::checkUsed(QTreeWidget *tree)
{
	_attributes->checkUsed(tree);
}
